package com.linx.common.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class HttpClientUtils {

    private static final int TIMEOUT = 50000;
    private static final CloseableHttpClient httpClient = HttpClients.custom()
        .setDefaultRequestConfig(RequestConfig.custom()
            .setSocketTimeout(TIMEOUT)
            .setConnectTimeout(TIMEOUT)
            .setConnectionRequestTimeout(TIMEOUT)
            .build())
        .build();

    public static String sendGet(String url, Map<String, String> parameters) throws IOException {
        // Build the query string from the parameters
        StringBuilder queryString = new StringBuilder();
        boolean isFirst = true;
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            if (!isFirst) {
                queryString.append("&");
            }
            isFirst = false;
            queryString.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8))
                .append("=")
                .append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
        }

        // Append the query string to the base URL
        url = url + "?" + queryString;
        HttpGet httpGet = new HttpGet(url);
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        }
    }
        public static String sendGet(String url, Map<String, String> parameters,Map<String, String> headerMap) throws IOException {
        // Build the query string from the parameters
        StringBuilder queryString = new StringBuilder();
        if (parameters != null && !parameters.isEmpty()) {
        boolean isFirst = true;
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            if (!isFirst) {
                queryString.append("&");
            }
            isFirst = false;
            queryString.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8))
                .append("=")
                .append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
        }
        url = url + "?" + queryString;
    }

       try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpGet httpGet = new HttpGet(url);

        // Add headers to the request
        if (headerMap != null && !headerMap.isEmpty()) {
            for (Map.Entry<String, String> header : headerMap.entrySet()) {
                httpGet.addHeader(header.getKey(), header.getValue());
            }
        }

        // Execute the request and return the response
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        }
    }
    }

    public static String sendPost(String url, String jsonPayload) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-type", "application/json");
        if(StringUtils.isNotEmpty(jsonPayload)){
            httpPost.setEntity(new StringEntity(jsonPayload, StandardCharsets.UTF_8));
        }
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        }
    }


    public static String sendPostForm(String url, String formData) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setEntity(new StringEntity(formData, StandardCharsets.UTF_8));
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        }
    }

    public static Map<String, String> httpGetBody(String url, String requestBody) {
        RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(5000) // 设置连接超时时间为5秒
            .setSocketTimeout(5000) // 设置请求超时时间为5秒
            .build();

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        httpPost.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));

        Map<String, String> resultMap = new HashMap<>();
        try {
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            String body = null;
            int status = 400;

            status = httpResponse.getStatusLine().getStatusCode();
            if (null != httpEntity) {
                body = EntityUtils.toString(httpEntity);
            }

            resultMap.put("status", String.valueOf(status));
            resultMap.put("body", body);

        } catch (ClientProtocolException e) {
            log.error("发送请求失败", e);
            throw new RuntimeException("发送请求失败", e);
        } catch (IOException e) {
            log.error("IO异常", e);
            throw new RuntimeException("IO异常", e);
        } finally {
            try {
                //关闭流，释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        return resultMap;
    }


    public static void main(String[] args) {
        try {
            //String responseGet = sendGet("https://api.example.com/data");
            //System.out.println("GET Response: " + responseGet);

            String jsonPayload = "{\"key\":\"value\"}";
            String responsePost = sendPost("https://api.example.com/submit", jsonPayload);
            System.out.println("POST Response: " + responsePost);

            String formData = "key1=value1&key2=value2";
            String responsePostForm = sendPostForm("https://api.example.com/form", formData);
            System.out.println("POST Form Response: " + responsePostForm);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
